package com.huage.courseplatform.application.controller;

import cn.dev33.satoken.annotation.SaCheckRole;
import cn.dev33.satoken.stp.StpUtil;
import com.huage.courseplatform.application.model.dto.StudentDTO;
import com.huage.courseplatform.application.model.dto.TeacherDTO;
import com.huage.courseplatform.application.model.entity.Business;
import com.huage.courseplatform.application.model.entity.Student;
import com.huage.courseplatform.application.model.entity.Teacher;
import com.huage.courseplatform.application.model.param.StudentPARAM;
import com.huage.courseplatform.application.model.param.TeacherPARAM;
import com.huage.courseplatform.application.model.vo.BusinessTeacherFlowRecordVO;
import com.huage.courseplatform.application.service.StudentService;
import com.huage.courseplatform.application.service.TeacherService;
import com.huage.courseplatform.framework.annotation.RepeatSubmit;
import com.huage.courseplatform.framework.api.AbstractController;
import com.huage.courseplatform.framework.enums.ResultCode;
import com.huage.courseplatform.framework.utils.ResultUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Update;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotEmpty;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping(value = "/student")
@Api(tags = "学生接口")
@Slf4j
public class StudentController extends AbstractController<Student, StudentDTO, StudentPARAM> {

    @Resource
    StudentService studentService;

    @RepeatSubmit
    @ApiOperation(value = "添加学生信息")
    @PostMapping(value = "/add")
    public ResultUtils<StudentDTO> add(@RequestBody @Validated({Insert.class}) StudentPARAM studentPARAM) {
        Student student = this.paramToEntity(studentPARAM);
        studentService.addAndBindUser(student,studentPARAM.getUserId());
        return ResultUtils.success(entityToDto(student));
    }

    @ApiOperation(value = "根据id删除学生信息")
    @DeleteMapping(value = "/delete/{id}")
    public ResultUtils<String> deleteById(@PathVariable String id) {
        Assert.isTrue(checkUserStudent(id),"用户权限不足");
        studentService.delStudentById(id);
        return ResultUtils.success("删除成功");
    }

    @ApiOperation(value = "根据id查询")
    @GetMapping(value = "/getById/{id}")
    public ResultUtils<StudentDTO> getById(@PathVariable String id) {
        Assert.isTrue(checkUserStudent(id),"用户权限不足");
        return ResultUtils.success(entityToDto(studentService.getById(id)));
    }


    @ApiOperation(value = "根据用户id查询学生列表")
    @GetMapping(value = "/getByUserId/{userId}")
    public ResultUtils<List<StudentDTO>> getByUserId(@PathVariable String userId) {
        String loginUserId = (String) StpUtil.getLoginId();
        if(!loginUserId.equals(userId)){
            return ResultUtils.error(ResultCode.FORBIDDEN.getCode(),ResultCode.FORBIDDEN.getMsg());
        }

        return ResultUtils.success(entityToDto(studentService.getByUserId(userId)));
    }

    @RepeatSubmit
    @ApiOperation(value = "更新")
    @PutMapping(value = "/update")
    public ResultUtils<StudentDTO> update(@RequestBody @Validated({Update.class}) StudentPARAM studentPARAM) {
        Assert.isTrue(checkUserStudent(studentPARAM.getId()),"用户权限不足");
        Student student = this.paramToEntity(studentPARAM);
        studentService.saveOrUpdate(student);
        return ResultUtils.success(entityToDto(student));
    }

    @ApiOperation(value = "绑定学生")
    @PostMapping(value = "/bindStudent")
    public ResultUtils<String> bindStudent(@NotEmpty(message = "用户id不能为空") String userId,
                                               @NotEmpty(message = "学生id不能为空") String studentId) {
        Assert.isTrue(checkUserStudent(studentId),"用户权限不足");
        studentService.bindUserStudent(userId,studentId);
        return ResultUtils.success("绑定成功");
    }


    @ApiOperation(value = "取消绑定学生")
    @PostMapping(value = "/unBindStudent")
    public ResultUtils<String> unBindStudent(@NotEmpty(message = "用户id不能为空") String userId,
                                           @NotEmpty(message = "学生id不能为空") String studentId) {

        Assert.isTrue(checkUserStudent(studentId),"用户权限不足");
        studentService.unBindUserStudent(userId,studentId);
        return ResultUtils.success("解绑成功");
    }



    /**
     * 根据学生Id判断当前用户是否存在关联学生
     * @param studentId
     * @return
     */
    private Boolean checkUserStudent(String studentId){
        if(!StpUtil.getRoleList().contains("ROLE_ADMIN")){
            //只允许修改本人
            String userId = (String) StpUtil.getLoginId();
            List<Student> userStudentList = studentService.getByUserId(userId);
            //判断商户id是否存在于集合
            Boolean isOwnBusiness = userStudentList.stream().map(Student::getId).collect(Collectors.toList()).contains(studentId);

            return isOwnBusiness;
        }
        return true;
    }

}
